package cn.wolfcode.trip.base.service.impl;

import cn.wolfcode.trip.base.domain.StrategyContent;
import cn.wolfcode.trip.base.domain.StrategyDetail;
import cn.wolfcode.trip.base.mapper.StrategyContentMapper;
import cn.wolfcode.trip.base.mapper.StrategyDetailMapper;
import cn.wolfcode.trip.base.query.StrategyDetailQueryObject;
import cn.wolfcode.trip.base.service.IStrategyDetailService;
import com.github.pagehelper.PageHelper;
import com.github.pagehelper.PageInfo;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.Date;
import java.util.List;

@Service
public class StrategyDetailServiceImpl implements IStrategyDetailService {
    @Autowired
    private StrategyDetailMapper strategyDetailMapper;
    @Autowired
    private StrategyContentMapper strategyContentMapper;

    @Override
    public PageInfo getPageInfo(StrategyDetailQueryObject qo) {
        PageHelper.startPage(qo.getCurrentPage(),qo.getPageSize());
        List<StrategyDetail> list = strategyDetailMapper.selectForList(qo);
        return new PageInfo(list);
    }



    @Override
    public void saveOrUpdate(StrategyDetail strategyDetail) {
        //如果用户没有传递序号 自动生成
        if(strategyDetail.getSequence()==null){
           int count = strategyDetailMapper.getMaxSequenceByCatalogId(strategyDetail.getCatalog().getId());
            strategyDetail.setSequence(++count);
        }
        //如果文章是发布状态创建时间
        if(strategyDetail.getState()==StrategyDetail.STATE_RELEASE){
            strategyDetail.setReleaseTime(new Date());
        }

        //获取文章的内容
        StrategyContent sc = strategyDetail.getStrategyContent();

        if(strategyDetail.getId()==null){
            //如果是新增攻略文章创建时间
            strategyDetail.setCreateTime(new Date());
            strategyDetailMapper.insert(strategyDetail);
            //新增文章内容
            sc.setId(strategyDetail.getId());
            strategyContentMapper.insert(sc);
        }else{
            strategyDetailMapper.updateByPrimaryKey(strategyDetail);
            //同步更新内容
            sc.setId(strategyDetail.getId());
            strategyContentMapper.updateByPrimaryKey(sc);
        }


    }

    @Override
    public StrategyDetail get(Long id) {
        StrategyDetail detail = strategyDetailMapper.selectByPrimaryKey(id);
        StrategyContent sc = strategyContentMapper.selectByPrimaryKey(id);
        detail.setStrategyContent(sc);
        return detail;
    }

}
